import React, { useMemo, useRef } from 'react';
import { Form, InputGroup } from 'react-bootstrap';
import type { FC } from 'react';
import { useTranslation } from 'react-i18next';

interface CustomFileInputProps {
  value: string;
  onChange: React.ChangeEventHandler<HTMLInputElement>;
  isValid?: boolean;
  isInvalid?: boolean;
}

const CustomFileInput: FC<CustomFileInputProps> = ({
  onChange,
  value,
  ...rest
}) => {
  const { t } = useTranslation('translation', { keyPrefix: 'editor' });
  const fileName = useMemo(() => {
    return value ?? t('file_upload.text');
  }, [value]);

  const fileRef = useRef<HTMLInputElement>(null);

  return (
    <Form.Group>
      <Form.Control
        type="file"
        id="custom-file"
        onChange={onChange}
        style={{ zIndex: -1, position: 'absolute' }} // 隐藏默认控件
        ref={fileRef}
        {...rest}
      />

      <InputGroup className="mb-3">
        <InputGroup.Text id="basic-addon1">
          {t('file_upload.text')}
        </InputGroup.Text>
        <Form.Control
          type="text"
          readOnly
          value={fileName}
          aria-label={t('file_upload.text')}
          placeholder={t('file_upload.placeholder')}
          aria-describedby="basic-addon1"
          onClick={() => {
            fileRef?.current?.click?.();
          }}
        />
      </InputGroup>
    </Form.Group>
  );
};

export default CustomFileInput;
